moonshine = require "moonshine"

require "util"
require "class"
require "const"
require "draw"
require "tile"
require "grid"
require "player"
require "bullet"
require "pattern"
require "goblin"
require "world"
require "title"
require "graphics-settings"
require "audio"

function love.load()
    loadFont()
    love.keyboard.setKeyRepeat(true)

    if love.graphics.isSupported then
        canvasSupported = love.graphics.isSupported("canvas")
    else
        canvasSupported = true
    end

    if canvasSupported then
        canvas = love.graphics.newCanvas(WWIDTH, WHEIGHT)

        fx = moonshine(moonshine.effects.filmgrain)
        for i, v in ipairs(graphicsSettings) do
            fx.chain(moonshine.effects[v[3]])
            fx.disable(v[3])
        end
    end

    state = "title"
    render()
end

function love.draw()
    if canvasSupported then
        fx(function()
            love.graphics.draw(canvas, 0, 0)
        end)
    else
        if state == "play" then
            drawText(text, world.message)
        else
            drawText(text, "")
        end
    end
end

function love.textinput(key)
    for i = 1, 1 do
        if state == "title" then
            restart()
            state = "play"
            sounds.toggle:play()
        elseif state == "help" then
            state = "play"
        elseif state == "graphics" then
            graphicsSettings.update(KEYS[key])
        elseif state == "play" then
            if world.player.dead then
                if KEYS[key] == ACTION.RESTART then
                    restart()
                end
                break
            end

            if KEYS[key] == ACTION.HELP then
                state = "help"
                break
            end

            if KEYS[key] == ACTION.GRAPHICS_SETTINGS then
                state = "graphics"
                break
            end

            if KEYS[key] then
                world:update(KEYS[key])
            end
        end
    end

    render()
end

function render()
    text = newGrid()
    if state == "title" then
        drawTitle(TITLE, text)
    elseif state == "help" then
        drawTitle(HELP, text)
    elseif state == "graphics" then
        graphicsSettings.render(text)
    elseif state == "play" then
        world:draw(text)
    end

    if canvasSupported then
        love.graphics.setCanvas(canvas)
        love.graphics.clear()
        if state == "play" then
            drawText(text, world:getFullMessage())
        else
            drawText(text, "")
        end
        love.graphics.setCanvas()
    end
end

function restart()
    world = World()
    render()
end
